package teamCservlets;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;


public class DefectFormsServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/* Requests supported by this servlet are:
		 * - display a data entry form for creating a new defect
		 * - display a form showing details of an existing defect
		 * - display the "close defect" data entry form
		 * - display the email creation form
		 */

		// Make sure a user is logged in, and if not, redirect to the login page
		PersonBean	authUser = null;
		HttpSession session = request.getSession();
		authUser = (PersonBean) session.getAttribute("user");
		if ((authUser == null) || (authUser.getId() == -1)) {
			response.sendRedirect("login.jsp");
		}

		// Determine which action is requested, and service the request.
		// The default action, if none other is specified, is to return
		// to the homepage.
		if (request.getParameter("btnCreateDefect") != null) {
			displayCreateDefect(request, response);
		} else if (request.getParameter("btnDisplayDefect") != null) {
			displayDefectDetails(request, response);
		} else if (request.getParameter("btnCloseDefect") != null) {
			closeDefect(request, response);
		} else if (request.getParameter("btnGoToHomepage") != null) {
			displayHomePage(request, response);
		} else if (request.getParameter("btnEmailDefect") != null) {
			displayEmailPage(request, response, authUser);
		} else {
			displayHomePage(request, response);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doPost(request, response);
	}

	private void displayCreateDefect(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// The user wants to create a new defect.  The steps are:
		// 1. Query the database for the list of applications, and store the list in
		// in the session. This will be used to build the application selection list.
		// 2. Query the database for the list of users, and store the list in
		// in the session. This will be used to build the assignee selection list.
		// (Note, there's some inefficiency here, the lists really need to be built
		// just once since this application doesn't provide an interface to add/delete
		// either applications or users.)
		// 3. Forward the request to the createdefect.jsp page, or in case of error,
		// display an error on status.jsp.

		String 		nextPage = null;
		DatabaseInterfaceApplication	dbApp = new DatabaseInterfaceApplication();
		DatabaseInterfacePerson			dbPerson = new DatabaseInterfacePerson();
		ArrayList<ApplicationBean>		appList = null;
		ArrayList<PersonBean>			personList = null;

        // Query the database for the list of applications.
        appList = dbApp.getApplicationList();

        // Query the database for the list of persons.
        personList = dbPerson.getPersonList();

		// Create a new defect object, which is initially invalid with ID = -1.  Add it to the
        // session, so that it's available to createdefect.jsp & the servlets.  In case the
        // user fails to enter a required field on the Create Defect form, the data will
        // be saved in this object so that it can be restored when the form is redisplayed.
		DefectBean newDefect = new DefectBean();
        HttpSession session = request.getSession();
		session.setAttribute("newDefect", newDefect);

		if ((appList == null) || (personList == null)) {

			// If either the application list or person list wasn't retrieved, for example,
			// error accessing the database, or the queried table was empty, this is an
			// unrecoverable error. Display the status page with an error message.
			request.setAttribute("msgType", "error");
			request.setAttribute("message", "Error in retrieving lists of applications and users from the database.");
			nextPage = "status.jsp";

		} else {

			// If all is OK, the next page to be displayed is the create defect page.
			nextPage = "createdefect.jsp";
			// Add the lists of applications and persons to the session, so that they
			// can be reused.
			session.setAttribute("applicationList", appList);
			session.setAttribute("personList", personList);
		}

		// Forward the request to the appropriate page or servlet, as determined above.
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);
	}

	private void displayDefectDetails(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// The user wants to view and possibly update an existing defect.  The steps are:
		// 1. Get data from the request, to determine which defect should be displayed.
		// 2. Query the database for that defect, getting a DefectBean, and store the
		// DefectBean in the request.
		// 3. Query the database for the list of users, and store the list in
		// in the request. This will be used to build the assignee selection list.
		// 4. Forward the request to the updatedefect.jsp page.

		DefectBean	defect = null;
		String 		nextPage = null;
		DatabaseInterfaceDefect		dbDefect = new DatabaseInterfaceDefect();
		DatabaseInterfacePerson		dbPerson = new DatabaseInterfacePerson();
		ArrayList<PersonBean>		personList = null;

		// Get the selected defect ID from the request, and query the database for it.
		if(request.getParameter("defectId") == null)
		{
			nextPage = "displayhomepage";
			request.setAttribute("defectlistmessage", "Please select a defect.");
		}
		else
		{

			int defectId = Integer.parseInt(request.getParameter("defectId"));

			defect = dbDefect.getOpenDefect(defectId);

	        // Query the database for the list of persons.
	        personList = dbPerson.getPersonList();

			if ((defect == null) || (personList == null)) {

				// If either the defect or person list wasn't retrieved, for example,
				// error accessing the database, or the queried table was empty, this is an
				// unrecoverable error. Display the status page with an error message.
				request.setAttribute("msgType", "error");
				request.setAttribute("message", "Error in retrieving a defect or list of users from the database.");
				nextPage = "status.jsp";

			} else {
				// If all is OK, the next page to be displayed is the defect details page.
				nextPage = "updatedefect.jsp";

				// Add the ID of the selected defect to the session, so that it's available  to
				// each jsp page & servlet that needs it.
				HttpSession session = request.getSession();
				session.setAttribute("currentDefectId", defectId);


				// Add the defect and list of persons to the session.
				session.setAttribute("currentDefect", defect);
				session.setAttribute("personList", personList);


				// Log some key details.  Here, we log the defect ID.
				int assigneeID = defect.getAssigneeID();

				int appID = defect.getApplicationID();

				// Next, get the application

				ApplicationBean defectApp;
				if(appID > 0) {
					DatabaseInterfaceApplication applicationInterface = new DatabaseInterfaceApplication();
					defectApp = applicationInterface.getApplication(appID);
				} else {
					defectApp = null;
				}

				request.setAttribute("defectApplication",defectApp);
			}
		}
		// Forward the request to the appropriate page or servlet, as determined above.
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);
	}

	private void closeDefect(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String 		nextPage = null;

		DefectBean	defect = null;
		HttpSession session = request.getSession();
		DatabaseInterfaceDefect		dbDefect = new DatabaseInterfaceDefect();
		int defectId = (Integer)session.getAttribute("currentDefectId");
		defect = dbDefect.getOpenDefect(defectId);

		if ((defect == null)) {

			// If either the defect wasn't retrieved, for example, error accessing the database,
			// display the status page with an error message.
			request.setAttribute("msgType", "error");
			request.setAttribute("message", "Error in retrieving the selected defect for closure from the database.");
			nextPage = "status.jsp";

		} else {

    		java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd");
    		java.util.Date date = new java.util.Date();

    		request.setAttribute("defectid", Integer.toString(defectId));
    		request.setAttribute("summary", defect.getSummary());
    		request.setAttribute("resolutiondate", dateFormat.format(date));
    		request.setAttribute("resolvemessage", "");

    		nextPage = "closedefect.jsp";

		}
		// Forward the request to the appropriate page or servlet, as determined above.
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);
	}

	private void displayEmailPage(HttpServletRequest request, HttpServletResponse response, PersonBean currentUser)
			throws ServletException, IOException {

		// The user wants to send an email about an existing defect.  The steps are:
		// 1. Determine which defect is the subject of the email.
		// 2. Query the database for that defect, getting a DefectBean.
		// 3. Query the database for the list of users, and store the list in
		// in the request. These will be the possible addressees.
		// 4. Build the email subject line to contain the defect ID and its status. Store the
		// subject line info in the request.
		// 5. Forward the request to the updatedefect.jsp page.

		DefectBean					defectToEmail = null;
		String 						nextPage = null;
		int							defectId;
		ArrayList<PersonBean>		personList = null;
		HttpSession 				session = request.getSession();

		// The user can get here from either the defect list or the update defect page.
		// If he was on the defect list, the selected defect should be in the request.  If
		// there's no defectId in the request, look in the session for currentDefectId.
		// If it's not found in either place, return the user to the defect list page.
		if (request.getParameter("defectId") == null)
		{
			defectId = (session.getAttribute("currentDefectId") == null ? -1 :
				(Integer)session.getAttribute("currentDefectId"));
		} else {
			defectId = Integer.parseInt(request.getParameter("defectId"));
		}

/*		// Display the data values
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Team C Defect System</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<p>Want to send email</p>");
		out.println("<p>Request's defectId parameter: " + request.getParameter("defectId") + "</p>");
		out.println("<p>Session's currentDefectId attribute: " + session.getAttribute("currentDefectId") + "</p>");
		out.println("</body>");
		out.println("</html>");
*/

		if (defectId == -1)
		{
			nextPage = "displayhomepage";
			request.setAttribute("defectlistmessage", "Please select a defect.");
		} else {
			// Defect ID has been found.

			// Query the database for the defect.
			DatabaseInterfaceDefect dbDefect = new DatabaseInterfaceDefect();
			defectToEmail = dbDefect.getOpenDefect(defectId);

			// Query the database for the list of persons.
			DatabaseInterfacePerson dbPerson = new DatabaseInterfacePerson();
	        personList = dbPerson.getPersonList();

			if ((defectToEmail == null) || (personList == null)) {

				// If either the defect or person list wasn't retrieved, for example,
				// error accessing the database, or the queried table was empty, this is an
				// unrecoverable error. Display the status page with an error message.
				request.setAttribute("msgType", "error");
				request.setAttribute("message", "Error in retrieving the selected defect or list of users from the database.");
				nextPage = "status.jsp";

			} else {
				// If all is OK, the next page to be displayed is the email page.
				nextPage = "emaildefect.jsp";

				// Build a subject line for the email, using the defect's ID, status,
				// and priority.
				String subjectLine = "Defect " + defectToEmail.getDefectID() + ", " +
						"status:" + defectToEmail.getStatus() + ", " +
						"priority:" + defectToEmail.getPriority();

				// Build a string for the email body, identifying who is sending this
				// message, because the sender's email address will always be the
				// mail account used to access the SMTP server.
				String emailClosingText = "This message was sent by " + currentUser.getFirstAndLastName() +
						". Replies will go to: " + currentUser.getEmailAddress();

				// Add the subject line, email text, and the current user's email address,
				// as the "reply to" address, to the request.
				request.setAttribute("subjectLine", subjectLine);
				request.setAttribute("emailClosingText", emailClosingText);
				request.setAttribute("replyTo", currentUser.getEmailAddress());

				// Add the list of persons to the session, so that the user can select
				// the email recipient.
				session.setAttribute("personList", personList);
			}
		}
		// Forward the request to the appropriate page or servlet, as determined above.
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);

	}

	private void displayHomePage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// Remove the ID of the previously selected defect, if there was one, from the session.
		// To take any action on a defect, the user has to select one first.
		HttpSession session = request.getSession();
		session.removeAttribute("currentDefectId");

		// To return to the homepage, set up the JSP forward, and forward the request
		// to the DisplayHomePageServlet.

		request.setAttribute("defectlistmessage", "");

		RequestDispatcher dispatcher = request.getRequestDispatcher("displayhomepage");
		dispatcher.forward(request, response);

	}
}
